# -*- coding: utf-8 -*-
# time: 2025/4/9 14:01
# file: his01.py
# author: hanson
"""
案例：
与消息历史集成的完整方案
"""
from langchain.chains.llm import LLMChain
from langchain_core.messages import HumanMessage, AIMessage
from langchain_community.chat_message_histories import ChatMessageHistory
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_ollama import ChatOllama
from langchain.memory import ConversationSummaryBufferMemory
from langchain_community.chat_message_histories import RedisChatMessageHistory

# 1. 创建带历史记录的提示模板
prompt = ChatPromptTemplate.from_messages([
    ("system", "你是一个专业助手"),
    MessagesPlaceholder(variable_name="history"),
    ("human", "{input}")
])

# 配置Redis连接参数
REDIS_URL = "redis://:1234qwer@192.168.6.43:6379/6"  # 密码前加冒号
# 1. 创建持久化消息历史（带Redis密码）
redis_history = RedisChatMessageHistory(
    session_id="user123",
    key_prefix="lang:history",
    url=REDIS_URL,
)
llm = ChatOllama(model="qwen2.5:1.5b")
# 2. 创建带摘要的缓冲记忆
memory = ConversationSummaryBufferMemory(
    llm=llm,
    chat_memory=redis_history,  # 使用Redis存储
    max_token_limit=1000,       # 触发摘要的token阈值
    memory_key="chat_history",
    return_messages=True
)

# 3. 创建链
llm = ChatOllama(model="qwen2.5:1.5b")
chain = LLMChain(llm=llm, prompt=prompt)

input_str="为什么Python适合AI开发？"
# 4. 带历史记录的调用
response = chain.invoke({
    "input": "为什么Python适合AI开发？",
    "history": redis_history.messages
})
print(response["text"])
# 5. 将新消息加入历史
redis_history.add_user_message(input_str)

# 查看结果（自动混合原始消息和摘要）
print(memory.load_memory_variables({}))